import TIM from 'tim-wx-sdk';
import TIMUploadPlugin from 'tim-upload-plugin';

let from;
let to;

let app = getApp();

let options = {
  SDKAppID: app.globalData.SDKAppID // SDKAppID
};

// 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
let tim = TIM.create(options); // SDK 实例通常用 tim 表示

//收到消息意味着可以进入咨询了
let onMessageReceived = function (event) {
  //注意，用户一定得是在排队中
  if (wx.getStorageSync('isWaiting') !== true) {
    return;
  }
  //第一步，更新缓存
  wx.setStorageSync('isWaiting', false);
  let cid = wx.getStorageSync("ongoingId");
  let rid = wx.getStorageSync("rid");
  //第二步，清除定时器
  app.timerStop();
  //第三步，跳转到聊天界面
  wx.redirectTo({
    url: '../chat/chat?cid=' + cid + '&rid=' + rid
  })
};

//必须全局监听，防止用户是切出该页面的
tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);

Page({

  /**
   * 页面的初始数据
   */
  data: {
    consultant: {},
    visitor: {},
    second: '00',
    minute: '00',
    hour: '00',
    consultRecordId: 0
  },

  cheat: function () {
    //第一步，更新缓存
    wx.setStorageSync('isWaiting', false);
    let cid = wx.getStorageSync("ongoingId");
    let rid = wx.getStorageSync("rid");
    //第二步，清除定时器
    app.timerStop();
    //第三步，跳转到聊天界面
    wx.redirectTo({
      url: '../chat/chat?cid=' + cid + '&rid=' + rid
    })
  },

  handleCancel: function () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确认要取消咨询吗',
      success(res) {
        if (res.confirm) {
          let temp = that.data.consultRecordId;
          //第一步，cancelConsult
          wx.request({
            url: app.globalData.prefix + '/visitor/cancelConsult/' + temp,
            success: (res) => {
              //第二步，给咨询师发一个特殊的消息
              let message = tim.createTextMessage({
                to: '' + to,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                  text: '--取消咨询--'
                },
                cloudCustomData: temp
              });
              let promise = tim.sendMessage(message);
              promise.then(function (imResponse) {
                console.log(imResponse);
              }).catch(function (imError) {
                console.warn('sendMessage error:', imError);
              });
              //第三步，更改缓存信息
              wx.removeStorageSync('ongoingId');
              wx.removeStorageSync('isWaiting');
              wx.removeStorageSync('rid');
              //第四步，清除定时器
              app.timerStop();
              //第五步，回退到主页
              wx.switchTab({
                url: '../index/index',
              })
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //开始计时
    if (!app.globalData.timerOn) {
      app.timerStart();
    }
    setInterval(() => {
      //每秒读取一次app中的时间
      this.setData({
        second: app.globalData.second,
        minute: app.globalData.minute,
        hour: app.globalData.hour,
      })
    }, 1000);

    from = wx.getStorageSync('userId');
    to = options.cid;

    //咨询师
    wx.request({
      url: app.globalData.prefix + '/consultant/getConsultantById/' + to,
      success: (res) => {
        this.setData({
          consultant: res.data.data
        })
      }
    });

    //访客
    wx.request({
      url: app.globalData.prefix + '/visitor/getVisitorById/' + from,
      success: (res) => {
        this.setData({
          visitor: res.data.data
        })
      }
    })

    let ongoingId = wx.getStorageSync('ongoingId');
    //只有当本来不在咨询中，才需要startConsult
    if (ongoingId === null || ongoingId === undefined || ongoingId === '') {
      //开始咨询
      //第一步，startConsult
      wx.request({
        url: app.globalData.prefix + '/visitor/startConsult',
        method: "POST",
        data: {
          fromId: from,
          toId: to
        },
        success: (res) => {
          console.log(res);
          let consultRecordId = res.data.data.consultRecordId;
          this.setData({
            consultRecordId
          });
          //第二步，给咨询师发一个特殊的消息
          let message = tim.createTextMessage({
            to: '' + to,
            conversationType: TIM.TYPES.CONV_C2C,
            payload: {
              text: 'hello'
            },
            cloudCustomData: "" + consultRecordId
          });
          let promise = tim.sendMessage(message);
          promise.then(function (imResponse) {
            console.log(imResponse);
          }).catch(function (imError) {
            console.warn('sendMessage error:', imError);
          });
          //第三步，更改缓存信息
          wx.setStorageSync('ongoingId', to);
          wx.setStorageSync('isWaiting', true);
          wx.setStorageSync('rid', consultRecordId);
        }
      })
    }
  },

})